<template>
  <div>
    <!-- :action="uploadAction" -->
    <!-- :data="{'fileStorageType':fileStorageType}" -->
    <!-- :headers="headers" -->
    <a-upload
      name="file"
      :multiple="multiple"
      :fileList="fileList"
      :beforeUpload="doBeforeUpload"
      @change="handleChange"
      :customRequest="customRequest"
      :disabled="disabled"
      listType="text"
      @preview="handlePreview"
      :class="{'uploadty-disabled':disabled}">
      <template>
        <a-button v-if="buttonVisible" :disabled="disabled">
         <a-icon type="upload" />{{ text }}
        </a-button>
      </template>
    </a-upload>
  </div>
</template>

<script>

// import { mapGetters } from 'vuex'
// import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Upload as AUpload } from 'ant-design-vue'
import { postAction } from '@/services/manage'
import { downloadFile, removeFile } from '@/services/common'
const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}

export default {
  name: 'ZUpload',
  components: { AUpload },
  data() {
    return {
      uploadAction: process.env.VUE_APP_API_BASE_URL + '/file/upload',
      headers: {},
      fileList: [],
      newFileList: [],
      previewVisible: false,
      previewImage: '',
      fileNames_: [], // 组件内部使用
      disaledInitFileList: false
    }
  },
  props: {
    text: {
      type: String,
      required: false,
      default: '点击上传'
    },
    value: {
      type: [String, Array],
      required: false
    },
    fileNames: { // 上传文件名
      type: [String, Array],
      required: false
    },
    fileStorageType: { // 文件存储类型FileSystem、Database
      type: String,
      default: () => 'FileSystem'
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    number: {
      type: Number,
      required: false,
      default: 0
    },
    buttonVisible: {
      type: Boolean,
      required: false,
      default: true
    },
    multiple: {
      type: Boolean,
      default: true
    },
    beforeUpload: {
      type: Function
    }
  },
  watch: {
    value: {
      immediate: true,
      handler() {
        const val = this.value
        if (val instanceof Array) {
          this.initFileListArr(val)
        } else {
          this.initFileListArr(val ? val.split(',') : [])
        }
      }
    }
    // token: {
    //   immediate: true,
    //   handler() {
    //     this.headers[ACCESS_TOKEN] = this.token
    //   }
    // }
  },
  computed: {
    // ...mapGetters(['token'])
  },
  methods: {
    customRequest(options) {
      const { onSuccess, file, onProgress, onError } = options
      const params = new FormData()
      params.append('file', file)
      params.append('fileStorageType', this.fileStorageType)
      postAction('/file/upload', params, {
        timeout: 60000,
        onUploadProgress: ({ total, loaded }) => {
          onProgress({ percent: Number(Math.round((loaded / total) * 100).toFixed(2)) }, file) // 显示上传进度
        }
      }).then(res => {
        onSuccess(res, file) // 成功返回值
      }).catch(onError)
    },
    initFileListArr(paths) {
      if (this.disaledInitFileList) {
        this.disaledInitFileList = false
        return
      }
      if (!paths || paths.length === 0) {
        this.fileList = []
        this.fileNames_ = []
        return
      }
      const fileList = []
      const fileNames = this.getFileName()
      paths.forEach((path, i) => {
        fileList.push({
          uid: uidGenerator(),
          name: fileNames[i] || path,
          status: 'done',
          url: path,
          response: {
            status: 'history',
            result: {
              fileName: fileNames[i] || path,
              fileNo: path
            }
          }
        })
      })
      this.fileList = fileList
    },
    getFileName() {
      if (this.fileNames_.length > 0) {
        return this.fileNames_
      }
      if (this.fileNames instanceof Array) {
        return this.fileNames
      } else {
        return this.fileNames ? this.fileNames.split(',') : []
      }
    },
    doBeforeUpload(file) {
      // 扩展 beforeUpload 验证
      if (typeof this.beforeUpload === 'function') {
        return this.beforeUpload(file)
      }
      return true
    },
    handleChange(info) {
      let fileList = info.fileList
      if (info.file.status === 'done') {
        if (!info.file.response) {
          fileList.forEach(item => {
            if (info.file.uid === item.uid) item.status = 'error'
          })
        }
        if (this.number > 0) {
          fileList = fileList.slice(-this.number)
        }
        if (info.file.response.success) {
          fileList = fileList.map((file) => {
            if (file.response) {
              file.name = file.response.result.fileName
              file.url = file.response.result.fileNo
            }
            return file
          })
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      } else if (info.file.status === 'removed') {
        this.handleDelete(info.file)
      }
      this.fileList = fileList
      if (info.file.status === 'done' || info.file.status === 'removed') {
        this.newFileList = []
        this.fileNames_ = []
        fileList.forEach(item => {
          if (item.status === 'done') {
            this.newFileList.push(item.url)
            this.fileNames_.push(item.name)
          } else {
            return
          }
        })
        this.disaledInitFileList = true
        this.$emit('change', this.value instanceof Array ? this.newFileList : this.newFileList.join(','))
        this.$emit('fileChange', this.fileList)
      }
    },
    handleDelete(file) { // 删除逻辑
      removeFile(file.url).then(res => {
        console.log(res)
      })
    },
    handlePreview(file) { // 文件下载
      downloadFile(file.url)
      return false
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style lang="less">
.uploadty-disabled{
  .ant-upload-list-item {
    .anticon-close{
      display: none;
    }
    .anticon-delete{
      display: none;
    }
  }
}
</style>
